//
//  MKScanController.m
//  Teleport
//
//  Created by RLY on 2020/6/2.
//  Copyright © 2020 xxt. All rights reserved.
//
//扫一扫
#import "TJScanController.h"
#import "MKScanView.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/PHPhotoLibrary.h>

@interface TJScanController ()<MLScanViewDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (weak, nonatomic) MKScanView *scanView;
@property (strong, nonatomic) UIActivityIndicatorView *activitydicator;


@end


@implementation TJScanController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addSubView];
}


- (void)addSubView {
    
    self.view.backgroundColor = UIColor.whiteColor;
    self.navigationBar.title = @"扫一扫".localizedString;
    self.navigationBar.alpha = 0;
    self.navigationBar.leftBarButton = [TJButtonBarButton barButtonBackButtonTarget:self action:@selector(dismissController)];;
    self.navigationBar.rightBarButton = [TJButtonBarButton barButtonWithTitle:@"相册".localizedString target:self action:@selector(didClickCameraButton)];
    [self.navigationBar.rightBarButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    self.navigationBar.titleTextColor = UIColor.whiteColor;
    [self.navigationBar backBarButtonWhiteColor];
    MKScanView *scanView = [[MKScanView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
    scanView.delegate = self;
    _scanView = scanView;
    [self.view addSubview:scanView];
}

- (void)didClickCameraButton {
    
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {}];
    
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
        [self alertWithTitle:nil message:@"不能访问您的相册，前往开启？".localizedString leftButtonName:@"取消".localizedString rightButtonName:@"前往开启".localizedString leftButtonBlock:nil rightButtonBlock:^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        }];
        return;
    }
    
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePickerController animated:YES completion:nil];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *scannedResult = @"";
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    if (!image) return;
    
    
    CIDetector*detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy : CIDetectorAccuracyHigh }];
    NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];
    if([features count] > 0){
        CIQRCodeFeature *feature = [features objectAtIndex:0];
        scannedResult = feature.messageString;
        //相册识别结果
        if (self.scanComplete) {
            self.scanComplete(scannedResult);
        }
        [self dismissToRootViewController];
    } else {
        [self alertWithTitle:@"提示".localizedString message:@"未识别到二维码".localizedString leftButtonName:@"确定".localizedString rightButtonName:nil leftButtonBlock:nil rightButtonBlock:nil];
    }
}

- (void)dismissController {
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark ---------------MLScanViewDelegate------------------
- (void)scanView:(MKScanView *)scanView resultString:(NSString *)resultString {
    self.activitydicator.hidden = NO;
    [self.activitydicator startAnimating];
    [self playSound];
    

    [self dismissViewControllerAnimated:YES completion:^{
        if (self.scanComplete) {
            self.scanComplete(resultString);
            TJLog(@"结果==%@",resultString);
        }
        
    }];
}

- (void)playSound {
    NSString *soundIDName = @"qrcode_completed.mp3";
    NSString *urlString = [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] pathForResource:soundIDName ofType:nil]];
    NSURL *url = [NSURL URLWithString:urlString];
    static SystemSoundID soundID = 10000;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)url, &soundID);
    AudioServicesPlaySystemSound(soundID);
}


- (UIActivityIndicatorView *)activitydicator {
    if (!_activitydicator) {
        _activitydicator = [[UIActivityIndicatorView alloc] init];
        if (KScreenHeight < 667) {
            _activitydicator.center = CGPointMake(self.view.center.x, self.view.center.y - 32);
        } else {
            _activitydicator.center = self.view.center;
        }
        [_activitydicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
        _activitydicator.transform = CGAffineTransformMakeScale(1.4, 1.6);
        _activitydicator.hidden = YES;
    }
    return _activitydicator;
}
 
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_scanView startRunning];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [_scanView stopRunning];
    [self.activitydicator stopAnimating];
 
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}


@end
